import 'dart:convert';
import 'dart:io';

import 'package:get/get.dart';

import 'package:http/http.dart' as http;

import 'package:image_picker/image_picker.dart';

import 'common.dart';

class ImageUploader {
  static Future uploadImage() async {
    Future<void> muploadImage(File image) async {
      try {
        var request = http.MultipartRequest(
          'POST',
          Uri.parse('$bsurl/bbs/upload'),
        );

        request.files.add(
          await http.MultipartFile.fromPath('file', image.path),
        );
        request.headers.addAll({'Authorization': myget('token') ?? ''});

        var response = await request.send();
        final responseString = await response.stream.bytesToString();
        if (response.statusCode == 200) {
          final jsonData = jsonDecode(responseString);

          return jsonData['data']['url'];
        } else {
          showTost(response.statusCode);
        }
      } catch (e) {
        showTost(e);
      } finally {}
    }

    final Rx<File?> selectedImage = Rx<File?>(null);

    try {
      // 选择图片  pickMultipleImages 多选pickImage
      final pickedFile = await ImagePicker().pickImage(
        source: ImageSource.gallery,
      );
      // await ImagePicker().pickMultiImage(limit: 9);

      if (pickedFile == null) return;

      // 更新选中图片
      final imageFile = File(pickedFile.path);
      selectedImage.value = imageFile;

      // 自动触发上传
      loading();
      return await muploadImage(imageFile);
    } catch (e) {}

    // 处理响应...
  }
}
